package com.supersit.greensproject.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.activity.BaseFragment;
import com.supersit.greensproject.adapter.PriceGatherBaseSelectAutoTvAdapter;
import com.supersit.greensproject.adapter.PriceGatherMaketSelectAutoTvAdapter;
import com.supersit.greensproject.entity.BaseBase;
import com.supersit.greensproject.entity.MaketSubject;
import com.supersit.greensproject.entity.PriceGather;
import com.supersit.greensproject.utils.T;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by cong on 2016/7/16.
 */
@ContentView(R.layout.fragment_price_gather_entering)
public class PirceGatherEnteringFragment extends BaseFragment {
    private Context context;
    @ViewInject(R.id.sp_area)
    private Spinner spMaketArea;
    @ViewInject(R.id.sp_maket_type)
    private Spinner spMaketType;
    @ViewInject(R.id.sp_merchandise)
    private Spinner spMerchandise;//类型 五大类

    @ViewInject(R.id.sp_detection_result)
    private Spinner spDetectionresult;//检测结果
    @ViewInject(R.id.et_business_licence_maket)
    private EditText etMaketBusinessLicence;//营业执照
    @ViewInject(R.id.aet_maket_name)
    private AutoCompleteTextView etMakteName;
    @ViewInject(R.id.et_market_address)
    private EditText etMaketAddress;
    @ViewInject(R.id.et_contacts)
    private EditText etContacts;
    @ViewInject(R.id.et_tel)
    private EditText etTel;
    @ViewInject(R.id.et_product_name)
    private EditText etProductName;//产品名称
    @ViewInject(R.id.et_form_base)
    private AutoCompleteTextView etFromBase;
    @ViewInject(R.id.et_average_price)
    private EditText etPrice;
    @ViewInject(R.id.et_number_of_transactions)
    private EditText etTransactionsNum;//交易数量
    @ViewInject(R.id.et_create_date)
    private EditText etCreateDate;
    @ViewInject(R.id.btn_save_data)
    private Button btnSaveData;
    private DbManager db;
    private PriceGather pg;
    private String[] columns = new String[]{"maketName", "id", "id as _id"};
    private PriceGatherMaketSelectAutoTvAdapter priceGatherAutoTvAdapter;
    String[] baseColumns = new String[]{"baseName", "id", "id as _id"};
    private PriceGatherBaseSelectAutoTvAdapter autoTvAdapter;
    private int maketId;
    private int baseId;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = getActivity();
        initVariable();
        bindListener();
    }

    private void initVariable() {
        ArrayAdapter maketAreaAdapter = ArrayAdapter.createFromResource(
                context, R.array.area, R.layout.spinner_text);
        maketAreaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spMaketArea.setAdapter(maketAreaAdapter);
        ArrayAdapter maketTypeAdapter = ArrayAdapter.createFromResource(
                context, R.array.maket_type, R.layout.spinner_text);
        maketTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spMaketType.setAdapter(maketTypeAdapter);
        ArrayAdapter merchandiseAdapter = ArrayAdapter.createFromResource(
                context, R.array.merchandise, R.layout.spinner_text);
        merchandiseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spMerchandise.setAdapter(merchandiseAdapter);
        ArrayAdapter detectionResultAdapter = ArrayAdapter.createFromResource(
                context, R.array.detection_result, R.layout.spinner_text);
        detectionResultAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spDetectionresult.setAdapter(detectionResultAdapter);
        etCreateDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        db = XUtilsDbManager.getInstance();
        /**设置字符数*/
        etMakteName.setThreshold(1);
        priceGatherAutoTvAdapter = new PriceGatherMaketSelectAutoTvAdapter(context, null, 0, columns);
        etMakteName.setAdapter(priceGatherAutoTvAdapter);
        /**设置字符数*/
        etFromBase.setThreshold(1);
        autoTvAdapter = new PriceGatherBaseSelectAutoTvAdapter(context, null, 0, baseColumns);
        etFromBase.setAdapter(autoTvAdapter);
        spMaketType.setEnabled(false);
        spMaketType.setClickable(false);
        spMaketArea.setEnabled(false);
        spMaketArea.setClickable(false);

    }

    private void bindListener() {
        btnSaveData.setOnClickListener(onClickListener);
        etMakteName.setOnItemClickListener(onItemClickListener);
        etMakteName.addTextChangedListener(textWatcher);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_save_data:
                    if (checkData()) {
                        saveData();
                    }
            }
        }
    };

    private void saveData() {
        String businessLicence;
        String maketName;
        String maketAddress;
        String contacts;
        String tel;
        String area;
        int maketType;
        String productName;
        int merchandises;//类型 五大类
        String fromBase;
        int detectionResult;//检测结果
        int ecification;//规格
        String price;
        String transactionsNum;
        String createDate;
        int maketID;
        int baseID;
        businessLicence = etMaketBusinessLicence.getText() == null ? "" : etMaketBusinessLicence.getText().toString();
        maketAddress = etMaketAddress.getText() == null ? "" : etMaketAddress.getText().toString();
        maketName = etMakteName.getText() == null ? "" : etMakteName.getText().toString();
        contacts = etContacts.getText() == null ? "" : etContacts.getText().toString();
        tel = etTel.getText() == null ? "" : etTel.getText().toString();
        String[] areas = getResources().getStringArray(R.array.area);
        area = areas[spMaketArea.getSelectedItemPosition()];
        maketType = spMaketType.getSelectedItemPosition();
        productName = etProductName.getText() == null ? "" : etProductName.getText().toString();
        merchandises = spMerchandise.getSelectedItemPosition();
        fromBase = etFromBase.getText() == null ? "" : etFromBase.getText().toString();
        detectionResult = spDetectionresult.getSelectedItemPosition();
        price = etPrice.getText() == null ? "" : etPrice.getText().toString();
        transactionsNum = etTransactionsNum.getText() == null ? "" : etTransactionsNum.getText().toString();
        createDate = etCreateDate.getText().toString();
        maketID = maketId;
        baseID = baseId;
        pg = new PriceGather();
        // db = MyApplication.db;
        pg.setBusinessLicence(businessLicence);
        pg.setMaketName(maketName);
        pg.setMaketAddress(maketAddress);
        pg.setContacts(contacts);
        pg.setTel(tel);
        pg.setMaketArea(area);
        pg.setMaketType(maketType);
        pg.setProductName(productName);
        pg.setMerchandise(merchandises);
        pg.setFromBase(fromBase);
        pg.setDetectionResult(detectionResult);
        pg.setAveragePrice(price);
        pg.setTransactionsNum(transactionsNum);
        pg.setCreateDate(createDate);
        pg.setOperationsTatus(1);
        pg.setIsDelete(1);
        pg.setBaseId(baseID);
        pg.setMaketId(maketID);

        try {
            db.saveBindingId(pg);
        } catch (DbException e) {
            e.printStackTrace();
        }
        resettingView();
        T.showShort(context, R.string.save_ok);
    }

    private boolean checkData() {
        boolean flag = false;

//        if (TextUtils.isEmpty(etMaketBusinessLicence.getText().toString())) {
//            T.showShort(context, R.string.BusinessLicence_is_not_null);
//            return flag;
//        }
        if (TextUtils.isEmpty(etMakteName.getText().toString())) {
            T.showShort(context, R.string.MakteName_is_not_null);
            return flag;
        }
//        if (TextUtils.isEmpty(etMaketAddress.getText().toString())) {
//            T.showShort(context, R.string.MaketAddress_is_not_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etContacts.getText().toString())) {
//            T.showShort(context, R.string.Contacts_is_not_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etTel.getText().toString())) {
//            T.showShort(context, R.string.Tel_is_not_null);
//            return flag;
//        }
        if (TextUtils.isEmpty(etProductName.getText().toString())) {
            T.showShort(context, R.string.ProductName_is_not_null);
            return flag;
        }
        if (TextUtils.isEmpty(etFromBase.getText().toString())) {
            T.showShort(context, R.string.FromBase_is_not_null);
            return flag;
        }
        if (TextUtils.isEmpty(etPrice.getText().toString())) {
            T.showShort(context, R.string.Price_is_not_null);
            return flag;
        }
        if (TextUtils.isEmpty(etTransactionsNum.getText().toString())) {
            T.showShort(context, R.string.TransactionsNum_is_not_null);
            return flag;
        }
        flag = true;
        return flag;
    }

    private void resettingView() {

        spMaketArea.setSelection(0);

        spMaketType.setSelection(0);

        spMerchandise.setSelection(0);//类型 五大类

        spDetectionresult.setSelection(0);//检测结果

        etMaketBusinessLicence.setText("");//营业执照

        etMakteName.setText("");

        etMaketAddress.setText("");

        etContacts.setText("");

        etTel.setText("");

        etProductName.setText("");//产品名称

        etFromBase.setText("");

        etPrice.setText("");

        etTransactionsNum.setText("");//交易数量

        // etCreateDate.setText("");
    }

    private void resettingViewPortion() {

        spMaketArea.setSelection(0);

        spMaketType.setSelection(0);

        spMerchandise.setSelection(0);//类型 五大类

        spDetectionresult.setSelection(0);//检测结果

        //etMakteName.setText("");

        etMaketAddress.setText("");

        etContacts.setText("");

        etTel.setText("");

        etMaketBusinessLicence.setText("");//营业执照
//        etProductName.setText("");//产品名称
//
//        etFromBase.setText("");
//
//        etPrice.setText("");
//
//        etTransactionsNum.setText("");//交易数量
//
//        etCreateDate.setText("");
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int mid = (int) view.getTag();
            try {
                MaketSubject ms = db.selector(MaketSubject.class).where("id", "=", mid).findFirst();
                if (null != ms) {
                    // T.showShort(context, ms.getBusinessLicence());
                    etMakteName.setText(ms.getMaketName() == null ? "" : ms.getMaketName());
                    etMaketBusinessLicence.setText(ms.getBusinessLicence());//营业执照
                    etMaketAddress.setText(ms.getMaketAddress() == null ? "" : ms.getMaketAddress());
                    etContacts.setText(ms.getOperator() == null ? "" : ms.getOperator());
                    etTel.setText(ms.getTel() == null ? "" : ms.getTel());
                    spMaketArea.setSelection(ms.getAreaId());
                    spMaketType.setSelection(ms.getCategory());
                    maketId = ms.getMaketId();
                }

            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    };
    private AdapterView.OnItemClickListener onItemClickListenerFromBase = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int mid = (int) view.getTag();
            try {
                BaseBase bb = db.selector(BaseBase.class).where("id", "=", mid).findFirst();
                if (null != bb) {
                    baseId = bb.getBaseId();
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    };
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            resettingViewPortion();
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

}
